package com.epam.cdp.ejb.timers;

import java.util.Date;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Singleton
public class TimerBean {

	private final static Log log = LogFactory.getLog(TimerBean.class);
	private int eventCounter = 5;
	
	@Resource
	private TimerService timerService;
	
    public TimerBean() {
        log.info("TimerBean created.");
    }

    @PostConstruct
    public void postConstruct() {
    	Timer timer = timerService.createTimer(2000, "Programatic timer");
    }
    
    @Timeout
    public void unallowedTimeoutMethod(Timer timer) {
    	log.info("unallowedTimeoutMethod");
    }
    
    @Timeout
    public void timeout(Timer timer) {
    	log.info("Programatic timer exired");
    }
    
	@Schedule(second = "*/3", minute = "*", hour = "*")
    public void scheduledTimeout(final Timer timer) {
		log.info("Method scheduledTimeout annotated with @Schedule called at: " + new Date());
		log.info("Next event will occur at " + timer.getNextTimeout());
		eventCounter--;
		if (eventCounter < 1) {
			timer.cancel();
			log.info("Automatic timer was canceled");
		}
    }
}